<?php


namespace App\Http\Controllers;


use App\Models\Admin;
use App\Models\MakeMaster;
use App\Models\ModelMaster;
use App\Models\Users;
use App\Models\Warranty;
use App\Services\UploadService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class ApiController extends Controller
{
    private const APP_KEY = '0338373e9f6a44ba4b2faed07f05df06';

    public function index(Request $request)
    {
        try {
            $this->checkRequestData($request);
        } catch (\Exception $exception) {
            return response()->json([
                'code'  => $exception->getCode() ?: 10000,
                'msg'   => $exception->getMessage() ?: '系统异常'
            ]);
        }
        $content = $request->input('content');
        $content = json_decode($content, true);
        if (empty($content['province'])) {
            return response()->json([
                'code'  => 1000,
                'message'   => '缺少省份数据'
            ]);
        }

        $province = $content['province'];
        $data = DB::table('province_master')->where('simplified_chiness_value', 'like', $province . '%')
            ->first();
        if (empty($data)) {
            return response()->json([
                'code'  => 1000,
                'message'   => '省份数据有误'
            ]);
        }

        if (!empty($content['city'])) {
            $city = DB::table('cities')->where('simplified_chiness_value', 'like', $content['city'] . '%')
                ->where('province_id', $data->id)
                ->first();
            if (empty($city)) {
                return response()->json([
                    'code'  => 1000,
                    'message'   => '市级数据有误'
                ]);
            }
        }

        $model = DB::table('users')
            ->leftJoin('store_info', 'users.id', 'store_info.user_id')
            ->leftJoin('dealer', 'users.id', 'dealer.user_id')
            ->leftJoin('cities', 'cities.id', 'users.city')
            ->leftJoin('province_master', 'province_master.id', 'users.province_id')
            ->where('users.province_id', $data->id);
        if (!empty($city)) {
            $model = $model->where('city', $city->id);
        }

        $firstData = $model
            ->select(
                'users.id',
                'users.company_name',
                'users.abbr',
                'users.address',
                'users.creator_id as dist_id',
                'users.email_address',
                'users.province_id',
                'users.phone_number',
                'users.zsdj',
                'cities.simplified_chiness_value as city_name',
                'users.mdtype',
                'province_master.simplified_chiness_value as province_name',
                'users.user_type',
                'dealer.store_pictures',
                'store_info.video_url',
                'store_info.detail',
                'users.unique_id as store_code',
                'store_info.open_time',
                'store_info.close_time',
                'store_info.start_date',
                'store_info.end_date',
                'store_info.picture_url',
                'dealer.cert_person as persons',
                'store_info.qrcode_url',
                'store_info.front_show',
                'store_info.is_advanced',
                'users.status',
                'store_info.honor',
                'users.check_status',
                'users.category_code',
                'users.category_name',
                'users.jsdj',
                'users.jsdj_number',
                'users.jshudj',
                'users.jshudj_number',
                'dealer.task_value'
            )
            ->whereNull('users.deleted_at')
            ->where('status', 1)
            ->where('users.creator_id', '!=', 299)
            ->where('mdtype', '!=', 5)
            ->where('mdtype', "!=", 2)
            ->orderByRaw(' CONVERT(abbr USING gbk)')
            ->get();

        if (empty($firstData)) {
            return response()->json([
                'code'  => 0,
                'data'  => []
            ]);
        }
        $result = [];
        $dealerIdArr = [];
        foreach ($firstData as $item) {
            if ($item->is_advanced == 1) {
                $dealerIdArr[] = $item->id;
                $result[] = $item;
            }
        }
        $dealerId = $firstData->pluck('id')->toArray();
        if (!empty($dealerId)) {
            $sql = 'SELECT SUM(xpel_warranty_roll_detail_stat.score) as total_score, dealer_id FROM xpel_warranty_roll_detail_stat WHERE dealer_id IN (' . implode(',', $dealerId) . ')';
            $sql .= ' AND product_type_id=1 AND create_date>="' . date("Y-m", strtotime('-1 month')) . '" AND create_date<"' . date("Y-m") . '" AND dealer_id!=dist_id';
            $sql .= ' GROUP BY dealer_id ORDER BY total_score DESC';
            $warrantyResult = DB::select($sql);
            if (!empty($warrantyResult)) {
                foreach ($warrantyResult as $item) {
                    if (in_array($item->dealer_id, $dealerIdArr)) {
                        continue;
                    }
                    $dealerIdArr[] = $item->dealer_id;
                    foreach ($firstData as $value) {
                        if ($value->id === $item->dealer_id) {
                            $result[] = $value;
                            break;
                        }
                    }
                }
            }
        }

        foreach ($firstData as $item) {
            if (!in_array($item->id, $dealerIdArr)) {
                $result[] = $item;
            }
        }

        $twoModel = DB::table('users')
            ->leftJoin('store_info', 'users.id', 'store_info.user_id')
            ->leftJoin('dealer', 'users.id', 'dealer.user_id')
            ->leftJoin('cities', 'cities.id', 'users.city')
            ->leftJoin('province_master', 'province_master.id', 'users.province_id')
            ->where('users.province_id', $data->id);
        if (!empty($city)) {
            $twoModel = $twoModel->where('city', $city->id);
        }
        $twoData = $twoModel
            ->select(
                'users.id',
                'users.company_name',
                'users.abbr',
                'users.address',
                'users.creator_id as dist_id',
                'users.email_address',
                'users.province_id',
                'users.phone_number',
                'users.zsdj',
                'cities.simplified_chiness_value as city_name',
                'users.mdtype',
                'province_master.simplified_chiness_value as province_name',
                'users.user_type',
                'dealer.store_pictures',
                'store_info.video_url',
                'store_info.detail',
                'users.unique_id as store_code',
                'store_info.open_time',
                'store_info.close_time',
                'store_info.start_date',
                'store_info.end_date',
                'store_info.picture_url',
                'dealer.cert_person as persons',
                'store_info.qrcode_url',
                'store_info.front_show',
                'store_info.is_advanced',
                'users.status',
                'store_info.honor',
                'users.check_status',
                'users.category_code',
                'users.category_name',
                'users.jsdj',
                'users.jsdj_number',
                'users.jshudj',
                'users.jshudj_number',
                'dealer.task_value'
            )
            ->whereNull('users.deleted_at')
            ->where('status', 1)
            ->where('users.creator_id', '!=', 299)
            ->where('mdtype', "=", 2)
            ->orderByRaw(' CONVERT(abbr USING gbk)')
            // 			->where('mdtype', "!=", 2) 
            ->get();

        if (!empty($twoData) && $twoData->isNotEmpty()) {
            $dealerIdArr = [];
            foreach ($twoData as $item) {
                if ($item->is_advanced == 1) {
                    $dealerIdArr[] = $item->id;
                    $result[] = $item;
                }
            }

            $dealerId = $twoData->pluck('id')->toArray();
            if (!empty($dealerId)) {
                $sql = 'SELECT SUM(xpel_warranty_roll_detail_stat.score) as total_score, dealer_id FROM xpel_warranty_roll_detail_stat WHERE dealer_id IN (' . implode(',', $dealerId) . ')';
                $sql .= ' AND product_type_id=1 AND create_date>="' . date("Y-m", strtotime('-1 month')) . '" AND create_date<"' . date("Y-m") . '" AND dealer_id!=dist_id';
                $sql .= ' GROUP BY dealer_id ORDER BY total_score DESC';
                $warrantyTwoResult = DB::select($sql);
                if (!empty($warrantyTwoResult)) {
                    foreach ($warrantyTwoResult as $item) {
                        if (in_array($item->dealer_id, $dealerIdArr)) {
                            continue;
                        }
                        $dealerIdArr[] = $item->dealer_id;
                        foreach ($twoData as $value) {
                            if ($value->id === $item->dealer_id) {
                                $result[] = $value;
                                break;
                            }
                        }
                    }
                }
            }

            foreach ($twoData as $item) {
                if (!in_array($item->id, $dealerIdArr)) {
                    $result[] = $item;
                }
            }
        }

        $sortType = [];
        foreach ($result as $key => $item) {
            if ($item->mdtype == 2) {
                $sortType[] = $result[$key];
                unset($result[$key]);
            }
        }
        $result = (object) array_merge((array) $result, (array) $sortType);

        $lists = [];
        $distID = [2244, 72, 82, 75, 86, 395, 79, 74, 404, 579, 908, 1059, 1070, 1302, 1304, 1825, 1839, 1903, 2170, 2179, 2182, 2200, 2207, 2210, 389, 649, 2353, 2446, 2775, 2776, 2956, 3357, 3369, 3373, 3523, 3521];
        foreach ($result as $item) {
            if (in_array($item->dist_id, $distID)) {
                $lists[] = $item;
            }
        }

        $response = [];
        foreach ($lists as $item) {
            unset($item->total_score);
            $item->status = $item->status == 1 && $item->check_status == 1 ? 1 : 0;
            $item->qrcode_url = $item->qrcode_url ? env('APP_URL') . $item->qrcode_url : '';
            if (!empty($item->store_pictures)) {
                $pictures = explode(',', $item->store_pictures);
                $item->picture_url = [];
                foreach ($pictures as $picture) {
                    $item->picture_url[] = env('APP_URL') . $picture;
                }
            } else {
                $item->picture_url = '';
            }

            if (!empty($item->mdtype)) {
                // $item->mdtype = $item->mdtype == 2 ? '授权店' : '旗舰店';
                if ($item->mdtype == 1) {
                    $item->mdtype = '外星人店';
                } else if ($item->mdtype == 2) {
                    $item->mdtype = '授权店';
                } else if ($item->mdtype == 3) {
                    $item->mdtype = '直营店';
                } else if ($item->mdtype == 4) {
                    $item->mdtype = '旗舰店';
                } else if ($item->mdtype == 5) {
                    $item->mdtype = '超级旗舰店';
                }
            } else {
                $item->mdtype = '';
            }
            if ($item->user_type === 2) {
                $item->store_code = '';
            }
            if (!empty($item->persons)) {
                $persons = json_decode($item->persons, true);
                if (!empty($persons)) {
                    $item->persons = $persons;
                }
            }

            $response[] = $item;
        }

        return response()->json([
            'code'  => 0,
            'data'  => $response
        ]);
    }

    /**
     * 按漆膜分数排序门店列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getList(Request $request)
    {
        try {
            $this->checkRequestData($request);
        } catch (\Exception $exception) {
            return response()->json([
                'code'  => $exception->getCode() ?: 10000,
                'msg'   => $exception->getMessage() ?: '系统异常'
            ]);
        }
        $content = $request->input('content');
        $content = json_decode($content, true);
        if (empty($content['province'])) {
            return response()->json([
                'code'  => 1000,
                'message'   => '缺少省份数据'
            ]);
        }

        $province = $content['province'];
        $provinceData = DB::table('province_master')->where('simplified_chiness_value', 'like', $province . '%')
            ->first();
        if (empty($provinceData)) {
            return response()->json([
                'code'  => 1000,
                'message'   => '省份数据有误'
            ]);
        }

        if (!empty($content['city'])) {
            $city = DB::table('cities')->where('simplified_chiness_value', 'like', $content['city'] . '%')
                ->where('province_id', $provinceData->id)
                ->first();
            if (empty($city)) {
                return response()->json([
                    'code'  => 1000,
                    'message'   => '市级数据有误'
                ]);
            }
        }

        $distID = [2244, 72, 82, 75, 86, 395, 79, 74, 404, 579, 908, 1059, 1070, 1302, 1304, 1825, 1839, 1903, 2170, 2179, 2182, 2200, 2207, 2210, 389, 649, 2353, 2446, 2775, 2776, 2956, 3357, 3369, 3373, 3523, 3521];

        $sql = 'SELECT SUM(xwrds.score) as total_score, xwrds.dealer_id as id';
        $sql .= ' FROM xpel_warranty_roll_detail_stat xwrds';
        $sql .= ' LEFT JOIN users ON users.id = xwrds.dealer_id';
        $sql .= ' LEFT JOIN store_info ON store_info.user_id = users.id';
        $sql .= ' LEFT JOIN province_master ON users.province_id = province_master.id';
        $sql .= ' LEFT JOIN cities ON users.city = cities.id';
        $sql .= ' WHERE users.creator_id IN (' . implode(',', $distID) . ')';
        $sql .= ' AND users.province_id = ' . $provinceData->id;
        if (!empty($city)) {
            $sql .= ' AND users.city = ' . $city->id;
        }
        $sql .= ' AND users.deleted_at IS NULL';
        $sql .= ' AND users.mdtype != 2';
        $sql .= ' AND users.mdtype != 5';
        $sql .= ' AND xwrds.product_type_id=1';
        $sql .= ' AND xwrds.create_date >="' . date("Y-m-01", strtotime('-1 month')) . '"';
        $sql .= ' AND xwrds.create_date < "' . date("Y-m-01", time()) . '"';
        $sql .= ' AND xwrds.dealer_id != xwrds.dist_id';
        $sql .= ' GROUP BY xwrds.dealer_id ORDER BY total_score DESC';
        $dealerScoreOne = DB::select($sql);
        $dealerScoreOneIds = [];
        foreach ($dealerScoreOne as $item) {
            $dealerScoreOneIds[] = $item->id;
        }
        $sql = 'SELECT users.id FROM users';
        $sql .= ' LEFT JOIN store_info ON store_info.user_id = users.id';
        $sql .= ' LEFT JOIN province_master ON users.province_id = province_master.id';
        $sql .= ' LEFT JOIN cities ON users.city = cities.id';
        $sql .= ' WHERE users.creator_id IN (' . implode(',', $distID) . ')';
        $sql .= ' AND users.province_id = ' . $provinceData->id;
        if (!empty($city)) {
            $sql .= ' AND users.city = ' . $city->id;
        }
        $sql .= ' AND users.deleted_at IS NULL';
        $sql .= ' AND users.mdtype != 2';
        $sql .= ' AND users.mdtype != 5';
        if (!empty($dealerScoreOneIds)) {
            $sql .= ' AND users.id NOT IN (' . implode(',', $dealerScoreOneIds) . ')';
        }
        $dealerIdsOne = DB::select($sql);
        $dealerIds = [];
        foreach ($dealerIdsOne as $item) {
            $dealerIds[] = $item->id;
        }
        $dealerIdsOne = array_merge($dealerScoreOneIds, $dealerIds);

        $sql = 'SELECT SUM(xwrds.score) as total_score, xwrds.dealer_id as id';
        $sql .= ' FROM xpel_warranty_roll_detail_stat xwrds';
        $sql .= ' LEFT JOIN users ON users.id = xwrds.dealer_id';
        $sql .= ' LEFT JOIN store_info ON store_info.user_id = users.id';
        $sql .= ' LEFT JOIN province_master ON users.province_id = province_master.id';
        $sql .= ' LEFT JOIN cities ON users.city = cities.id';
        $sql .= ' WHERE users.creator_id IN (' . implode(',', $distID) . ')';
        $sql .= ' AND users.province_id = ' . $provinceData->id;
        if (!empty($city)) {
            $sql .= ' AND users.city = ' . $city->id;
        }
        $sql .= ' AND users.deleted_at IS NULL';
        $sql .= ' AND users.mdtype = 2';
        $sql .= ' AND users.mdtype != 5';
        $sql .= ' AND xwrds.product_type_id=1';
        $sql .= ' AND xwrds.create_date >="' . date("Y-m-01", strtotime('-1 month')) . '"';
        $sql .= ' AND xwrds.create_date < "' . date("Y-m-01", time()) . '"';
        $sql .= ' AND xwrds.dealer_id != xwrds.dist_id';
        $sql .= ' GROUP BY xwrds.dealer_id ORDER BY total_score DESC';
        $dealerScoreTwo = DB::select($sql);
        $dealerScoreTwoIds = [];
        foreach ($dealerScoreTwo as $item) {
            $dealerScoreTwoIds[] = $item->id;
        }

        $sql = 'SELECT users.id FROM users';
        $sql .= ' LEFT JOIN store_info ON store_info.user_id = users.id';
        $sql .= ' LEFT JOIN province_master ON users.province_id = province_master.id';
        $sql .= ' LEFT JOIN cities ON users.city = cities.id';
        $sql .= ' WHERE users.creator_id IN (' . implode(',', $distID) . ')';
        $sql .= ' AND users.province_id = ' . $provinceData->id;
        if (!empty($city)) {
            $sql .= ' AND users.city = ' . $city->id;
        }
        $sql .= ' AND users.deleted_at IS NULL';
        $sql .= ' AND users.mdtype = 2';
        $sql .= ' AND users.mdtype != 5';
        if (!empty($dealerScoreTwoIds)) {
            $sql .= ' AND users.id NOT IN (' . implode(',', $dealerScoreTwoIds) . ')';
        }
        $dealerIdsTwo = DB::select($sql);
        $dealerIds = [];
        foreach ($dealerIdsTwo as $item) {
            $dealerIds[] = $item->id;
        }
        $dealerIdsTwo = array_merge($dealerScoreTwoIds, $dealerIds);
        $dealerIds = array_merge($dealerIdsOne, $dealerIdsTwo);
        $response = [];
        foreach ($dealerIds as $dealerId) {
            $item = DB::table('users')
                ->leftJoin('store_info', 'users.id', 'store_info.user_id')
                ->leftJoin('dealer', 'users.id', 'dealer.user_id')
                ->leftJoin('cities', 'cities.id', 'users.city')
                ->leftJoin('province_master', 'province_master.id', 'users.province_id')
                ->select(
                    'users.id',
                    'users.company_name',
                    'users.abbr',
                    'users.address',
                    'users.creator_id as dist_id',
                    'users.email_address',
                    'users.province_id',
                    'users.phone_number',
                    'users.zsdj',
                    'cities.simplified_chiness_value as city_name',
                    'users.mdtype',
                    'province_master.simplified_chiness_value as province_name',
                    'users.user_type',
                    'users.top100',
                    'dealer.store_pictures',
                    'store_info.video_url',
                    'store_info.detail',
                    'users.unique_id as store_code',
                    'store_info.open_time',
                    'store_info.close_time',
                    'store_info.start_date',
                    'store_info.end_date',
                    'store_info.picture_url',
                    'dealer.cert_person as persons',
                    'store_info.qrcode_url',
                    'store_info.front_show',
                    'store_info.is_advanced',
                    'store_info.persons as rzjs',
                    'users.status',
                    'store_info.honor',
                    'users.check_status',
                    'users.category_code',
                    'users.category_name',
                    'users.jsdj',
                    'users.jsdj_number',
                    'users.jshudj',
                    'users.jshudj_number',
                    'dealer.task_value'
                )
                ->where('users.id', $dealerId)
                ->first();
            if (empty($item)) {
                continue;
            }
            //            $item->start_date =  date("Y-m-01", strtotime('-1 month'));
            //            $item->end_date = date("Y-m-01",time());
            $item->status = $item->status == 1 && $item->check_status == 1 ? 1 : 0;
            $item->qrcode_url = $item->qrcode_url ? env('APP_URL') . $item->qrcode_url : '';
            if (!empty($item->store_pictures)) {
                $pictures = explode(',', $item->store_pictures);
                $item->picture_url = [];
                foreach ($pictures as $picture) {
                    $item->picture_url[] = env('APP_URL') . $picture;
                }
            } else {
                $item->picture_url = '';
            }

            if (!empty($item->mdtype)) {
                // $item->mdtype = $item->mdtype == 2 ? '授权店' : '旗舰店';
                if ($item->mdtype == 1) {
                    $item->mdtype = '外星人店';
                } else if ($item->mdtype == 2) {
                    $item->mdtype = '授权店';
                } else if ($item->mdtype == 3) {
                    $item->mdtype = '直营店';
                } else if ($item->mdtype == 4) {
                    $item->mdtype = '旗舰店';
                } else if ($item->mdtype == 5) {
                    $item->mdtype = '超级旗舰店';
                }
            } else {
                $item->mdtype = '';
            }
            if ($item->user_type === 2) {
                $item->store_code = '';
            }
            if (!empty($item->persons)) {
                $persons = json_decode($item->persons, true);
                if (!empty($persons)) {
                    $item->persons = $persons;
                }
            }

            $response[] = $item;
        }

        return response()->json([
            'code'  => 0,
            'data'  => $response
        ]);
    }

    /**
     * 报价系统数据接口
     */
    public function getAll(Request $request)
    {
        try {
            $this->checkRequestData($request);
        } catch (\Exception $exception) {
            return response()->json([
                'code'  => $exception->getCode() ?: 10000,
                'msg'   => $exception->getMessage() ?: '系统异常'
            ]);
        }
        $content = $request->input('content');
        $content = json_decode($content, true);
        if (empty($content['page'])) {
            return response()->json([
                'code'  => 10000,
                'msg'   => '缺少分页数据'
            ]);
        }
        $page = $content['page'];
        $pageSize = $content['pageSize'] ?? 20;

        $model = DB::table('users')
            ->leftJoin('store_info', 'users.id', 'store_info.user_id')
            ->leftJoin('dealer', 'users.id', 'dealer.user_id')
            ->leftJoin('cities', 'cities.id', 'users.city')
            ->leftJoin('province_master', 'province_master.id', 'users.province_id');

        $total = $model
            ->select(
                'users.id',
                'users.company_name',
                'users.abbr',
                'users.address',
                'users.email_address',
                'users.phone_number',
                'users.zsdj',
                'users.jsdj',
                'cities.simplified_chiness_value as city_name',
                'users.mdtype',
                'province_master.simplified_chiness_value as province_name',
                'users.user_type',
                'dealer.store_pictures',
                'store_info.video_url',
                'store_info.detail',
                'store_info.performance_pledge',
                'users.unique_id as store_code',
                'store_info.open_time',
                'store_info.close_time',
                'store_info.start_date',
                'store_info.end_date',
                'store_info.picture_url',
                'store_info.persons',
                'store_info.qrcode_url',
                'store_info.front_show',
                'store_info.is_advanced',
                'users.status',
                'users.top100',
                'store_info.honor',
                'users.check_status',
                'users.category_code',
                'users.category_name'
            )
            ->whereNull('users.deleted_at')
            ->where('status', 1)
            ->where('check_status', 1)
            ->where('users.user_type', 3)
            ->whereNotIn('mdtype', [5, 7])
            ->count();

        $firstData = $model
            ->select(
                'users.id',
                'users.company_name',
                'users.abbr',
                'users.address',
                'users.email_address',
                'users.phone_number',
                'users.zsdj',
                'users.jsdj',
                'cities.simplified_chiness_value as city_name',
                'users.mdtype',
                'province_master.simplified_chiness_value as province_name',
                'users.user_type',
                'dealer.store_pictures',
                'store_info.video_url',
                'store_info.detail',
                'store_info.performance_pledge',
                'users.unique_id as store_code',
                'store_info.open_time',
                'store_info.close_time',
                'store_info.start_date',
                'store_info.end_date',
                'store_info.picture_url',
                'store_info.persons',
                'store_info.qrcode_url',
                'store_info.front_show',
                'store_info.is_advanced',
                'users.status',
                'users.top100',
                'store_info.honor',
                'users.check_status',
                'users.category_code',
                'users.category_name'
            )
            ->whereNull('users.deleted_at')
            ->where('status', 1)
            ->where('check_status', 1)
            ->where('users.user_type', 3)
            ->whereNotIn('mdtype', [5, 7])
            ->orderByRaw(' CONVERT(abbr USING gbk)')
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->get();

        $count = 0;
        $result = [];
        if (!empty($firstData) && !$firstData->isEmpty()) {
            $result = [];
            $dealerIdArr = [];
            foreach ($firstData as $item) {
                if ($item->is_advanced == 1) {
                    $dealerIdArr[] = $item->id;
                    $result[] = $item;
                }
            }

            $dealerId = $firstData->pluck('id')->toArray();

            $sql = 'SELECT SUM(xpel_warranty_roll_detail_stat.score) as total_score, dealer_id FROM xpel_warranty_roll_detail_stat WHERE dealer_id IN (' . implode(',', $dealerId) . ')';
            $sql .= ' AND product_type_id=1 AND create_date>="' . date("Y-m", strtotime('-1 month')) . '" AND create_date<"' . date("Y-m") . '" AND dealer_id!=dist_id';
            $sql .= ' GROUP BY dealer_id ORDER BY total_score DESC';
            $warrantyResult = DB::select($sql);
            if (!empty($warrantyResult)) {
                foreach ($warrantyResult as $item) {
                    if (in_array($item->dealer_id, $dealerIdArr)) {
                        continue;
                    }
                    $dealerIdArr[] = $item->dealer_id;
                    foreach ($firstData as $value) {
                        if ($value->id === $item->dealer_id) {
                            $result[] = $value;
                            break;
                        }
                    }
                }
            }

            foreach ($firstData as $item) {
                if (!in_array($item->id, $dealerIdArr)) {
                    $result[] = $item;
                }
            }

            $count = count($result);
        }
        if ($count < $pageSize) {
            if ($count > 0) {
                $start = 0;
            } else {
                $start = ($page - 1) * $pageSize - $total;
            }
            $twoModel = DB::table('users')
                ->leftJoin('store_info', 'users.id', 'store_info.user_id')
                ->leftJoin('dealer', 'users.id', 'dealer.user_id')
                ->leftJoin('cities', 'cities.id', 'users.city')
                ->leftJoin('province_master', 'province_master.id', 'users.province_id');
            $twoData = $twoModel
                ->select(
                    'users.id',
                    'users.company_name',
                    'users.abbr',
                    'users.address',
                    'users.email_address',
                    'users.phone_number',
                    'users.zsdj',
                    'users.jsdj',
                    'cities.simplified_chiness_value as city_name',
                    'users.mdtype',
                    'province_master.simplified_chiness_value as province_name',
                    'users.user_type',
                    'dealer.store_pictures',
                    'store_info.video_url',
                    'store_info.detail',
                    'store_info.performance_pledge',
                    'users.unique_id as store_code',
                    'store_info.open_time',
                    'store_info.close_time',
                    'store_info.start_date',
                    'store_info.end_date',
                    'store_info.picture_url',
                    'store_info.persons',
                    'store_info.qrcode_url',
                    'store_info.front_show',
                    'store_info.is_advanced',
                    'users.status',
                    'store_info.honor',
                    'users.check_status'
                )
                ->whereNull('users.deleted_at')
                ->where('check_status', 1)
                ->where('status', 1)
                ->where('users.user_type', 3)
                ->where('mdtype', '!=', 5)
                ->offset($start)
                ->limit($pageSize)
                ->orderByRaw(' CONVERT(abbr USING gbk)')
                ->get();

            if (!empty($twoData) && $twoData->isNotEmpty()) {
                $dealerIdArr = [];
                foreach ($twoData as $item) {
                    if ($item->is_advanced == 1) {
                        $dealerIdArr[] = $item->id;
                        $result[] = $item;
                    }
                }

                $dealerId = $twoData->pluck('id')->toArray();
                $sql = 'SELECT SUM(xpel_warranty_roll_detail_stat.score) as total_score, dealer_id FROM xpel_warranty_roll_detail_stat WHERE dealer_id IN (' . implode(',', $dealerId) . ')';
                $sql .= ' AND product_type_id=1 AND create_date>="' . date("Y-m", strtotime('-1 month')) . '" AND create_date<"' . date("Y-m") . '" AND dealer_id!=dist_id';
                $sql .= ' GROUP BY dealer_id ORDER BY total_score DESC';
                $warrantyTwoResult = DB::select($sql);
                if (!empty($warrantyTwoResult)) {
                    foreach ($warrantyTwoResult as $item) {
                        if (in_array($item->dealer_id, $dealerIdArr)) {
                            continue;
                        }
                        $dealerIdArr[] = $item->dealer_id;
                        foreach ($twoData as $value) {
                            if ($value->id === $item->dealer_id) {
                                $result[] = $value;
                                break;
                            }
                        }
                    }
                }
                foreach ($twoData as $item) {
                    if (!in_array($item->id, $dealerIdArr)) {
                        $result[] = $item;
                    }
                }
            }
        }

        $response = [];
        foreach ($result as $item) {
            unset($item->total_score);
            $item->status = $item->status == 1 && $item->check_status == 1 ? 1 : 0;
            $item->qrcode_url = $item->qrcode_url ? env('APP_URL') . $item->qrcode_url : '';
            if (!empty($item->store_pictures)) {
                $pictures = explode(',', $item->store_pictures);
                $item->picture_url = [];
                foreach ($pictures as $picture) {
                    $item->picture_url[] = env('APP_URL') . $picture;
                }
            } else {
                $item->picture_url = '';
            }

            if (!empty($item->mdtype)) {
                $item->mdtype = $item->mdtype == 2 ? '授权店' : '旗舰店';
            } else {
                $item->mdtype = '';
            }
            if ($item->user_type === 2) {
                $item->store_code = '';
            }
            if (!empty($item->persons)) {
                $persons = json_decode($item->persons, true);
                if (!empty($persons)) {
                    $item->persons = $persons;
                }
            } else {
                $item->persons = [];
            }

            $response[] = $item;
        }

        return response()->json([
            'code'  => 0,
            'data'  => $response
        ]);
    }

    public function getNewAll(Request $request)
    {
        try {
            $this->checkRequestData($request);
        } catch (\Exception $exception) {
            return response()->json([
                'code'  => $exception->getCode() ?: 10000,
                'msg'   => $exception->getMessage() ?: '系统异常'
            ]);
        }
        $content = $request->input('content');
        $content = json_decode($content, true);
        if (empty($content['page'])) {
            return response()->json([
                'code'  => 10000,
                'msg'   => '缺少分页数据'
            ]);
        }
        $page = $content['page'];
        $pageSize = $content['pageSize'] ?? 20;
        $model = DB::table('users')
            ->leftJoin('store_info', 'users.id', 'store_info.user_id')
            ->leftJoin('dealer', 'users.id', 'dealer.user_id')
            ->leftJoin('cities', 'cities.id', 'users.city')
            ->leftJoin('province_master', 'province_master.id', 'users.province_id');

        $stores = $model
            ->select(
                'users.company_name',
                'users.abbr',
                'users.address',
                'users.status',
                'users.phone_number',
                'users.zsdj',
                'cities.simplified_chiness_value as city_name',
                'province_master.simplified_chiness_value as province_name',
                'users.unique_id as store_code',
                'users.status',
                'users.category_code',
                'users.category_name',
                'store_info.detail',
                'mdtype'
            )
            ->whereNull('users.deleted_at')
            //->where('status', 1)
            ->where('check_status', 1)
            ->where('users.user_type', 3)
            ->whereNotIn('mdtype', [5, 6])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->get();

        return response()->json([
            'code'  => 0,
            'data'  => $stores
        ]);
    }

    public function area(Request $request)
    {
        try {
            $this->checkRequestData($request);
        } catch (\Exception $exception) {
            return response()->json([
                'code'  => $exception->getCode() ?: 10000,
                'msg'   => $exception->getMessage() ?: '系统异常'
            ]);
        }
        $content = $request->input('content');
        $content = json_decode($content, true);

        if (empty($content['province'])) {
            $province = DB::table('province_master')->select('english_value', 'traditional_chiness_value', 'simplified_chiness_value')->whereNull('deleted_at')->get();
            if (empty($province)) {
                return response()->json([
                    'code'      => 1000,
                    'message'   => '暂未查询到数据'
                ]);
            }

            return response()->json([
                'code'  => 0,
                'data'  => $province
            ]);
        }

        $province = $content['province'];
        $data = DB::table('province_master')->where('simplified_chiness_value', 'like', $province . '%')
            ->first();
        if (empty($data)) {
            return response()->json([
                'code'  => 1000,
                'message'   => '省份数据有误'
            ]);
        }

        $city = DB::table('cities')
            ->select('id', 'english_value', 'traditional_chiness_value', 'simplified_chiness_value')
            ->where('province_id', $data->id)
            ->get();
        if (empty($city)) {
            return response()->json([
                'code'  => 1000,
                'message'   => '未查询到市级数据'
            ]);
        }

        return response()->json([
            'code'  => 0,
            'data'  => $city
        ]);
    }

    public function checkRequestData(Request $request)
    {
        $sign = $request->input('sign');
        $content = $request->input('content');
        if (empty($content)) {
            throw new \Exception('缺少数据', 10000);
        }
        if (empty($sign)) {
            throw new \Exception('缺少签名数据', 10000);
        }
        if (is_array($content)) {
            $content = json_encode($content);
        }
        if (md5($content . self::APP_KEY) !== $sign) {
            throw new \Exception('签名校验失败,直接复制签名值:' . md5($content . self::APP_KEY), 10000);
        }

        return true;
    }

    public function stat(Request $request)
    {
        try {
            $this->checkRequestData($request);
        } catch (\Exception $exception) {
            return response()->json([
                'code'  => $exception->getCode() ?: 10000,
                'msg'   => $exception->getMessage() ?: '系统异常'
            ]);
        }
        $content = $request->input('content');
        $content = json_decode($content, true);
        if (empty($content['province'])) {
            return response()->json([
                'code'  => 1000,
                'message'   => '缺少省份数据'
            ]);
        }

        $province = $content['province'];
        $data = DB::table('province_master')->where('simplified_chiness_value', 'like', $province . '%')
            ->first();
        if (empty($data)) {
            return response()->json([
                'code'  => 1000,
                'message'   => '省份数据有误'
            ]);
        }

        $users = DB::table('users')->where('province_id', $data->province_id)
            ->where('user_type', 2)
            ->where('status', 1)
            ->get();

        return [
            'users' => $users
        ];
    }

    public function detail(Request $request)
    {

        try {
            $this->checkRequestData($request);
        } catch (\Exception $exception) {
            return response()->json([
                'code'  => $exception->getCode() ?: 10000,
                'msg'   => $exception->getMessage() ?: '系统异常'
            ]);
        }
        $content = $request->input('content');
        $content = json_decode($content, true);
        if (empty($content['store_name']) && empty($content['store_code'])) {
            return response()->json([
                'code'  => 1000,
                'message'   => '缺少数据'
            ]);
        }

        $model = DB::table('users')
            ->leftJoin('dealer', 'users.id', 'dealer.user_id')
            ->leftJoin('store_info', 'users.id', 'store_info.user_id')
            ->leftJoin('cities', 'cities.id', 'users.city')
            ->leftJoin('province_master', 'province_master.id', 'users.province_id');

        if (!empty($content['store_name'])) {
            $model = $model->where('users.abbr', 'like', '%' . $content['store_name'] . '%');
        }

        if (!empty($content['store_code'])) {
            $model = $model->where('users.unique_id', 'like', '%' . $content['store_code'] . '%');
        }

        $data = $model
            ->select(
                'users.id',
                'users.company_name',
                'users.abbr',
                'users.address',
                'users.email_address',
                'users.phone_number',
                'users.zsdj',
                'cities.simplified_chiness_value as city_name',
                'users.mdtype',
                'province_master.simplified_chiness_value as province_name',
                'store_info.video_url',
                'dealer.store_pictures',
                'store_info.detail',
                'users.unique_id as store_code',
                'store_info.open_time',
                'store_info.close_time',
                'store_info.start_date',
                'store_info.end_date',
                'store_info.picture_url',
                'store_info.persons',
                'store_info.qrcode_url',
                'store_info.front_show',
                'store_info.is_advanced',
                'users.status',
                'store_info.honor',
                'users.check_status',
                'users.jsdj',
                'users.jsdj_number',
                'users.jshudj',
                'users.jshudj_number',
                'dealer.task_value',
                'store_info.performance_pledge'
            )
            ->whereNull('users.deleted_at')
            ->orderBy('mdtype', 'desc')
            ->get();
        return response()->json([
            'code'  => 0,
            'data'  => $data
        ]);
        if (empty($data) || $data->isEmpty()) {
            return response()->json([
                'code'  => 0,
                'data'  => []
            ]);
        }

        foreach ($data as &$item) {
            $item->status = $item->status == 1 && $item->check_status == 1 ? 1 : 0;
            $item->qrcode_url = $item->qrcode_url ? env('APP_URL') . $item->qrcode_url : '';
            if (!empty($item->store_pictures)) {
                $pictures = explode(',', $item->store_pictures);
                $item->picture_url = [];
                foreach ($pictures as $picture) {
                    $item->picture_url[] = env('APP_URL') . $picture;
                }
            } else {
                $item->picture_url = '';
            }

            if (!empty($item->mdtype)) {
                $item->mdtype = $item->mdtype === 2 ? '授权店' : '旗舰店';
            } else {
                $item->mdtype = '';
            }
            if (!empty($item->persons)) {
                $persons = json_decode($item->persons, true);
                if (!empty($persons)) {
                    $item->persons = $persons;
                }
            } else {
                $item->persons = [];
            }
        }

        return response()->json([
            'code'  => 0,
            'data'  => $data
        ]);
    }

    public function getDetail(Request $request)
    {
        try {
            $this->checkRequestData($request);
        } catch (\Exception $exception) {
            return response()->json([
                'code'  => $exception->getCode() ?: 10000,
                'msg'   => $exception->getMessage() ?: '系统异常'
            ]);
        }
        $content = $request->input('content');
        $content = json_decode($content, true);
        if (empty($content['store_name']) && empty($content['store_code'])) {
            return response()->json([
                'code'  => 1000,
                'message'   => '缺少数据'
            ]);
        }

        $model = DB::table('users')
            ->leftJoin('dealer', 'users.id', 'dealer.user_id')
            ->leftJoin('store_info', 'users.id', 'store_info.user_id')
            ->leftJoin('cities', 'cities.id', 'users.city')
            ->leftJoin('province_master', 'province_master.id', 'users.province_id');

        if (!empty($content['store_name'])) {
            $model = $model->where('users.abbr', $content['store_name']);
        }

        if (!empty($content['store_code'])) {
            $model = $model->where('users.unique_id', $content['store_code']);
        }

        $data = $model
            ->select(
                'users.id',
                'users.company_name',
                'users.abbr',
                'users.address',
                'users.email_address',
                'users.phone_number',
                'users.zsdj',
                'cities.simplified_chiness_value as city_name',
                'users.mdtype',
                'province_master.simplified_chiness_value as province_name',
                'store_info.detail',
                'users.unique_id as store_code',
                'users.province_id',
                'users.region_id',
                'users.city'
            )
            ->whereNull('users.deleted_at')
            ->orderBy('mdtype', 'desc')
            ->first();

        if (empty($data)) {
            return response()->json([
                'code'  => 0,
                'data'  => []
            ]);
        }

        return response()->json([
            'code'  => 0,
            'data'  => $data
        ]);
    }
    /**
     * 获取店铺信息列表
     *
     * @param Request $request
     */
    public function getStoreList(Request $request)
    {
        try {
            $this->checkRequestData($request);
        } catch (\Exception $exception) {
            return response()->json([
                'code'  => $exception->getCode() ?: 10000,
                'msg'   => $exception->getMessage() ?: '系统异常'
            ]);
        }
        $content = $request->input('content');
        $content = json_decode($content, true);
        $page = $content['page'] ?: 1;
        $pageSize = $content['page_size'] ?: 20;
        $model = DB::table('users')
            ->leftJoin('store_info', 'users.id', 'store_info.user_id')
            ->leftJoin('dealer', 'users.id', 'dealer.user_id')
            ->leftJoin('cities', 'cities.id', 'users.city')
            ->leftJoin('province_master', 'province_master.id', 'users.province_id');

        $stores = $model
            ->select(
                'users.company_name',
                'users.abbr',
                'users.address',
                'users.phone_number',
                'users.zsdj',
                'users.top100',
                'cities.simplified_chiness_value as city_name',
                'province_master.simplified_chiness_value as province_name',
                'users.unique_id as store_code',
                'users.status',
                'users.category_code',
                'users.category_name'
            )
            ->whereNull('users.deleted_at')
            ->where('status', 1)
            ->whereIn('users.user_type', [1, 2])
            ->where('users.creator_id', '!=', 299)
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->orderByRaw(' CONVERT(abbr USING gbk)')
            ->get();

        return response()->json([
            'code'  => 0,
            'data'  => $stores
        ]);
    }

    public function addWarranty(Request $request)
    {
        try {
            $this->checkRequestData($request);
        } catch (\Exception $exception) {
            return response()->json([
                'code'  => $exception->getCode() ?: 10000,
                'msg'   => $exception->getMessage() ?: '系统异常'
            ]);
        }
        DB::beginTransaction();
        try {
            $model = new Warranty();
            $model = wSave($model);


            $year_id = $request->input('year_id');
            $make_name = $request->input('make_id');
            $model_name = $request->input('model_id');
            $make_id = getMakeId($make_name, $year_id);
            if (empty($make_id)) {
                $makeModel = new MakeMaster();
                $makeModel->year_id = $request->input('year_id');
                $makeModel->english_value = $make_name;
                $makeModel->traditional_chiness_value = $make_name;
                $makeModel->simplified_chiness_value = $make_name;
                $makeModel->save();
                $msg[] = "系统中不存在年份车辆品牌，已自动新增，请确认英文、繁体、简体内容是否正确：" . $year_id . ' / ' . $make_name;
                $make_id = $makeModel->id;

                makeLangFiles();
            }
            $model_id = getModelId($model_name, $make_id);
            if (empty($model_id)) {
                $modelModel = new ModelMaster();
                $modelModel->make_id = $make_id;
                $modelModel->english_value = $model_name;
                $modelModel->traditional_chiness_value = $model_name;
                $modelModel->simplified_chiness_value = $model_name;
                $modelModel->save();
                $msg[] = "系统中不存在品牌车辆型号，已自动新增，请确认英文、繁体、简体内容是否正确：" . $year_id . ' / ' . $model_name . ' / ' . $make_name;
                $model_id = $modelModel->id;
                makeLangFiles();
            }
            $model->make_id = $make_id;
            $model->model_id = $model_id;
            $model->approved = 3;
            $model->save();

            if (empty($model->pre_id)) {
                rwC($model); // 更新安装部位
            }
            rwI($model); // 更新安装图片

            $res = []; //vWV4($model->id);
            if (!empty($res)) {
                DB::rollback(); //数据库回滚
                $error_msg = @$res[0] ?: '服务器错误，稍后重试！';
                return response()->json([
                    'code'  => 3,
                    'msg'   => $error_msg
                ]);
            } else {
                $dealer = Admin::withTrashed()->find($model->user_id);
                if (empty($dealer->id) || empty($dealer->abbr)) {
                    DB::rollback();
                    return response()->json([
                        'code'  => 1,
                        'msg'   => '装贴门店为空或不存在！',
                    ]);
                }
                if ($dealer->user_type == 3) {
                    $distributor = Admin::withTrashed()->find($dealer->creator_id);
                    if (empty($distributor->id) || empty($distributor->abbr)) {
                        DB::rollback();
                        return response()->json([
                            'code'  => 2,
                            'msg'   => '装贴门店所属不存在！'
                        ]);
                    }
                } else {
                    $distributor = $dealer;
                }
                $model->dealer_name = $dealer->abbr;
                $model->distributor_id = $distributor->id;
                $model->distributor_name = $distributor->abbr;
                $model->save();
            }
            //            $coverages = WarrantyToVehicleCoverage::where('warranty_id', $model->id)
            //                ->get(['roll_number', 'length', 'part_id']);
            //            foreach ($coverages as $k => $v) {
            //                $roll = RollMaster::where('roll_number', $v->roll_number)->first();
            //                if (empty($roll)) {
            //                    DB::rollback();
            //                    return redirect()->back()->withInput()->with('trash', ['content'=> '卷号不存在，稍后重试！', 'type'=>'error']);
            //                }
            //                $roll->status = 2;
            //                $roll->save();
            //                $e = minusRestlen($model->user_id, $v->roll_number, $v->length);
            //                if (empty($e)) {
            //                    DB::rollback();
            //                    return redirect()->back()->withInput()->with('trash', ['content'=> '服务器错误，稍后重试！', 'type'=>'error']);
            //                }
            //            }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollback(); //数据库回滚
            return response()->json([
                'code'  => 1000,
                'msg'   => '服务器错误,稍后重试！'
            ]);
        }

        return response()->json([
            'code'  => 0,
            'msg'   => 'success',
            'warranty_id'   => $model->warranty_id
        ]);
    }

    public function getProviderList(Request $request)
    {
        try {
            $this->checkRequestData($request);
        } catch (\Exception $exception) {
            return response()->json([
                'code'  => $exception->getCode() ?: 10000,
                'msg'   => $exception->getMessage() ?: '系统异常'
            ]);
        }
        $content = $request->input('content');
        $content = json_decode($content, true);
        if (empty($content['page'])) {
            return response()->json([
                'code'  => 10000,
                'msg'   => '缺少分页数据'
            ]);
        }
        $page = $content['page'];
        $pageSize = $content['pageSize'] ?? 200;

        $model = DB::table('users')
            ->leftJoin('store_info', 'users.id', 'store_info.user_id')
            ->leftJoin('dealer', 'users.id', 'dealer.user_id')
            ->leftJoin('cities', 'cities.id', 'users.city')
            ->leftJoin('province_master', 'province_master.id', 'users.province_id');

        $total = $model
            ->select(
                'users.id',
                'users.company_name',
                'users.abbr',
                'users.address',
                'users.email_address',
                'users.phone_number',
                'users.zsdj',
                'cities.simplified_chiness_value as city_name',
                'users.mdtype',
                'province_master.simplified_chiness_value as province_name',
                'users.user_type',
                'dealer.store_pictures',
                'store_info.video_url',
                'store_info.detail',
                'users.unique_id as store_code',
                'store_info.open_time',
                'store_info.close_time',
                'store_info.start_date',
                'store_info.end_date',
                'store_info.picture_url',
                'dealer.cert_person as persons',
                'store_info.qrcode_url',
                'store_info.front_show',
                'store_info.is_advanced',
                'users.status',
                'store_info.honor',
                'users.check_status',
                'users.category_code',
                'users.category_name'
            )
            ->whereNull('users.deleted_at')
            ->where('status', 1)
            ->where('users.user_type', 3)
            ->where('mdtype', '=', 6)
            ->count();
        $firstData = $model
            ->select(
                'users.id',
                'users.company_name',
                'users.abbr',
                'users.address',
                'users.email_address',
                'users.phone_number',
                'users.zsdj',
                'cities.simplified_chiness_value as city_name',
                'users.mdtype',
                'province_master.simplified_chiness_value as province_name',
                'users.user_type',
                'dealer.store_pictures',
                'store_info.video_url',
                'store_info.detail',
                'users.unique_id as store_code',
                'store_info.open_time',
                'store_info.close_time',
                'store_info.start_date',
                'store_info.end_date',
                'store_info.picture_url',
                'dealer.cert_person as persons',
                'store_info.qrcode_url',
                'store_info.front_show',
                'store_info.is_advanced',
                'users.status',
                'store_info.honor',
                'users.check_status',
                'users.category_code',
                'users.category_name'
            )
            ->whereNull('users.deleted_at')
            ->where('status', 1)
            ->where('mdtype', '=', 6)
            ->orderByRaw(' CONVERT(abbr USING gbk)')
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->get();
        $count = 0;
        // $result = [];
        if (!empty($firstData) && !$firstData->isEmpty()) {
            $result = [];
            $dealerIdArr = [];
            foreach ($firstData as $item) {
                if ($item->is_advanced == 1) {
                    $dealerIdArr[] = $item->id;
                    $result[] = $item;
                }
            }

            $dealerId = $firstData->pluck('id')->toArray();

            $sql = 'SELECT SUM(xpel_warranty_roll_detail_stat.score) as total_score, dealer_id FROM xpel_warranty_roll_detail_stat WHERE dealer_id IN (' . implode(',', $dealerId) . ')';
            $sql .= ' AND product_type_id=1 AND create_date>="' . date("Y-m", strtotime('-1 month')) . '" AND create_date<"' . date("Y-m") . '" AND dealer_id!=dist_id';
            $sql .= ' GROUP BY dealer_id ORDER BY total_score DESC';
            $warrantyResult = DB::select($sql);
            if (!empty($warrantyResult)) {
                foreach ($warrantyResult as $item) {
                    if (in_array($item->dealer_id, $dealerIdArr)) {
                        continue;
                    }
                    $dealerIdArr[] = $item->dealer_id;
                    foreach ($firstData as $value) {
                        if ($value->id === $item->dealer_id) {
                            $result[] = $value;
                            break;
                        }
                    }
                }
            }

            // foreach ($firstData as $item) {
            //     if (!in_array($item->id, $dealerIdArr)) {
            //         $result[] = $item;
            //     }
            // }

            $count = count($result);
        }

        if ($count < $pageSize) {
            if ($count > 0) {
                $start = 0;
            } else {
                $start = ($page - 1) * $pageSize - $total;
            }
            $twoModel = DB::table('users')
                ->leftJoin('store_info', 'users.id', 'store_info.user_id')
                ->leftJoin('dealer', 'users.id', 'dealer.user_id')
                ->leftJoin('cities', 'cities.id', 'users.city')
                ->leftJoin('province_master', 'province_master.id', 'users.province_id');
            $twoData = $twoModel
                ->select(
                    'users.id',
                    'users.company_name',
                    'users.abbr',
                    'users.address',
                    'users.email_address',
                    'users.phone_number',
                    'users.zsdj',
                    'cities.simplified_chiness_value as city_name',
                    'users.mdtype',
                    'province_master.simplified_chiness_value as province_name',
                    'users.user_type',
                    'dealer.store_pictures',
                    'store_info.video_url',
                    'store_info.detail',
                    'users.unique_id as store_code',
                    'store_info.open_time',
                    'store_info.close_time',
                    'store_info.start_date',
                    'store_info.end_date',
                    'store_info.picture_url',
                    'dealer.cert_person as persons',
                    'store_info.qrcode_url',
                    'store_info.front_show',
                    'store_info.is_advanced',
                    'users.status',
                    'store_info.honor',
                    'users.check_status'
                )
                ->whereNull('users.deleted_at')
                ->where('status', 1)
                ->where('users.user_type', 3)
                ->where('mdtype', "=", 6)
                ->offset($start)
                ->limit($pageSize)
                ->orderByRaw(' CONVERT(abbr USING gbk)')
                ->get();
            if (!empty($twoData) && $twoData->isNotEmpty()) {
                $dealerIdArr = [];
                foreach ($twoData as $item) {
                    if ($item->is_advanced == 1) {
                        $dealerIdArr[] = $item->id;
                        $result[] = $item;
                    }
                }

                $dealerId = $twoData->pluck('id')->toArray();
                $sql = 'SELECT SUM(xpel_warranty_roll_detail_stat.score) as total_score, dealer_id FROM xpel_warranty_roll_detail_stat WHERE dealer_id IN (' . implode(',', $dealerId) . ')';
                $sql .= ' AND product_type_id=1 AND create_date>="' . date("Y-m", strtotime('-1 month')) . '" AND create_date<"' . date("Y-m") . '" AND dealer_id!=dist_id';
                $sql .= ' GROUP BY dealer_id ORDER BY total_score DESC';
                $warrantyTwoResult = DB::select($sql);
                if (!empty($warrantyTwoResult)) {
                    foreach ($warrantyTwoResult as $item) {
                        if (in_array($item->dealer_id, $dealerIdArr)) {
                            continue;
                        }
                        $dealerIdArr[] = $item->dealer_id;
                        foreach ($twoData as $value) {
                            if ($value->id === $item->dealer_id) {
                                $result[] = $value;
                                break;
                            }
                        }
                    }
                }
                foreach ($twoData as $item) {
                    if (!in_array($item->id, $dealerIdArr)) {
                        $result[] = $item;
                    }
                }
            }
        }

        $response = [];
        foreach ($result as $item) {
            unset($item->total_score);
            $item->status = $item->status == 1 && $item->check_status == 1 ? 1 : 0;
            $item->qrcode_url = $item->qrcode_url ? env('APP_URL') . $item->qrcode_url : '';
            if (!empty($item->store_pictures)) {
                $pictures = explode(',', $item->store_pictures);
                $item->picture_url = [];
                foreach ($pictures as $picture) {
                    $item->picture_url[] = env('APP_URL') . $picture;
                }
            } else {
                $item->picture_url = '';
            }

            $item->mdtype = '家居建筑膜服务商';
            if ($item->user_type === 2) {
                $item->store_code = '';
            }
            if (!empty($item->persons)) {
                $persons = json_decode($item->persons, true);
                if (!empty($persons)) {
                    $item->persons = $persons;
                }
            }

            $response[] = $item;
        }

        return response()->json([
            'code'  => 0,
            'data'  => $response
        ]);
    }

    public function getRank(Request $request)
    {
        try {
            $this->checkRequestData($request);
        } catch (\Exception $exception) {
            return response()->json([
                'code'  => $exception->getCode() ?: 10000,
                'msg'   => $exception->getMessage() ?: '系统异常'
            ]);
        }
        $content = $request->input('content');
        $content = json_decode($content, true);
        if (empty($content)) {
            return response()->json([
                'code'  => 10001,
                'msg'   => '参数不合法'
            ]);
        }
        $startMonth = $content['month'] ?? date('Y-m-01');
        $endMonth = date('Y-m-d', strtotime("$startMonth +1 month"));

        $sql = "SELECT sum(qm_score) as total_score, users.unique_id, users.abbr FROM xpel_dealer_stat";
        $sql .= " LEFT JOIN users ON xpel_dealer_stat.dealer_id=users.id";
        $sql .= " WHERE create_month >= \"$startMonth \"AND create_month < \"$endMonth\"";
        $sql .= " AND dealer_id != 1 AND dist_id != 1";
        $sql .= " GROUP BY dealer_id ORDER BY total_score DESC";
        $dealers = DB::select($sql);


        if (!empty($dealers) && is_array($dealers)) {
            foreach ($dealers as $dealer) {
                $qm_list[] = [
                    'code' => $dealer->unique_id,
                    'name' => $dealer->abbr
                ];
            }
        }

        $sql = "SELECT sum(win_score) as total_score, users.unique_id,users.abbr FROM xpel_dealer_stat";
        $sql .= " LEFT JOIN users ON xpel_dealer_stat.dealer_id=users.id";
        $sql .= " WHERE create_month >= \"$startMonth \"AND create_month < \"$endMonth\"";
        $sql .= " AND dealer_id != 1 AND dist_id != 1";
        $sql .= " GROUP BY dealer_id ORDER BY total_score DESC";
        $dealers = DB::select($sql);
        $win_list = array_column($dealers, 'abbr', 'unique_id');
        if (!empty($dealers) && is_array($dealers)) {
            foreach ($dealers as $dealer) {
                $win_list[] = [
                    'shop_code' => $dealer->unique_id,
                    'name' => $dealer->abbr
                ];
            }
        }
        $data['qm_list'] = $qm_list;
        $data['win_list'] = $win_list;
        return response()->json([
            'code' => 0,
            'data' => $data
        ]);
    }

    //店铺膜月度排名
    public function getFilmRank(Request $request)
    {
        try {
            $this->checkRequestData($request);
        } catch (\Exception $exception) {
            return response()->json([
                'code'  => $exception->getCode() ?: 10000,
                'msg'   => $exception->getMessage() ?: '系统异常'
            ]);
        }
        $content = $request->input('content');
        $content = json_decode($content, true);
        if (empty($content)) {
            return response()->json([
                'code'  => 10001,
                'msg'   => '参数不合法'
            ]);
        }
        $shopCode = $content['shop_code'] ?? "";
        $month = $content['month'] ?? date('Y-m');
        if (empty($shopCode)) {
            return response()->json([
                'code'  => 10001,
                'msg'   => '参数不合法'
            ]);
        }
        if (empty($month) && !isMonth($month)) {
            return response()->json([
                'code'  => 10001,
                'msg'   => '参数不合法'
            ]);
        }
        $startMonth = date('Y-m-01', strtotime($month));
        $endMonth = date('Y-m-d', strtotime("$startMonth +1 month"));
        $user = (new Users())::where('unique_id', $shopCode)->first();
        if (empty($user)) {
            return response()->json([
                'code'  => 10001,
                'msg'   => '参数不合法'
            ]);
        }

        $sql = "SELECT film_type_id, film_name, sum(num) AS num FROM xpel_dealer_roll_stat";
        $sql .= " WHERE dealer_id= {$user->id} AND product_type_id= 1";
        $sql .= " AND create_month >= \"{$startMonth} \"AND create_month < \"{$endMonth}\"";
        $sql .= "  GROUP BY film_type_id ORDER BY num DESC";
        $qmData = DB::select($sql);

        $sql = "SELECT film_type_id, film_name, sum(num) AS num FROM xpel_dealer_roll_stat";
        $sql .= " WHERE dealer_id= {$user->id} AND product_type_id= 2";
        $sql .= " AND create_month >= \"{$startMonth} \"AND create_month < \"{$endMonth}\"";
        $sql .= "  GROUP BY film_type_id  ORDER BY num DESC";
        $winData = DB::select($sql);

        $data['qm_list'] = $qmData;
        $data['win_list'] = $winData;
        return response()->json([
            'code' => 0,
            'data' => $data
        ]);
    }

    //新增质保数据
    public function addNewWarranty(Request $request)
    {
        try {
            $this->checkRequestData($request);
            $params = $request->all();
            $rule = [
                'first_name' => 'required|string',
                'province' => 'required|string',
                'city' => 'required|string',
                'email' => 'required|email',
                'phone_number' => 'required|string',
                'address' => 'required|string',
                'year' => 'required|integer',
                'make_name' => 'required|string',
                'model_name' => 'required|string',
                'shop' => 'required|string',
                'shop_code' => 'required|string',
                'license_plate' => 'required|string',
                'vin_number' => 'required|string',
                'installer_name' => 'required|string',
                'installation_date' => 'required|string',
                'installation_price' => 'required|integer|min:1',
                'images' => 'required|string',
                'converages' => 'required|array|min:1',
            ];
            $message = [
                'first_name.required' => '姓名不能为空',
                'province.required' => '省份不能为空',
                'city.required' => '城市不能为空',
                'email.required' => '邮箱不能为空',
                'phone_number.required' => '电话号码不能为空',
                'address.required' => '地址不能为空',
                'year.required' => '年份不能为空',
                'make_name.required' => '品牌名称不能为空',
                'model_name.required' => '车型名称不能为空',
                'shop.required' => '门店名称不能为空',
                'shop_code.required' => '门店编码不能为空',
                'license_plate.required' => '车牌号不能为空',
                'vin_number.required' => 'VIN码不能为空',
                'installer_name.required' => '安装师傅姓名不能为空',
                'installation_date.required' => '安装日期不能为空',
                'installation_price.required' => '安装价格不能为空且大于0.01元',
                'images.required' => '图片不能为空',
                'converages.required' => '安装位置不能为空',
                'converages.min' => '至少选择一个安装位置'
            ];
            $validator = Validator::make($params, $rule, $message);
            if ($validator->fails()) {
                return response()->json([
                    'code' => 1000,
                    'message' => $validator->errors()
                ]);
            }
            $dealer = Admin::withTrashed()->where('unique_id', $params['shop_code'])->first();
            if (empty($dealer->id) || empty($dealer->abbr)) {
                return response()->json([
                    'code' => 1,
                    'msg' => '装贴门店为空或不存在！',
                ]);
            }
            $distributor = $dealer;
            if ($dealer->user_type == 3) {
                $distributor = Admin::withTrashed()->find($dealer->creator_id);
                if (empty($distributor->id) || empty($distributor->abbr)) {
                    return response()->json([
                        'code' => 2,
                        'msg' => '装贴门店所属不存在！'
                    ]);
                }
            }
            if ($dealer->abbr != $params['shop']) {
                return response()->json([
                    'code' => 3,
                    'msg' => '装贴门店名称不匹配！'
                ]);
            }
            $provinceData = DB::table('province_master')->where('simplified_chiness_value', 'like', $params['province'] . '%')
                ->first();
            if (empty($provinceData)) {
                return response()->json([
                    'code' => 1000,
                    'message' => '省份数据有误'
                ]);
            }

            $city = DB::table('cities')->where('simplified_chiness_value', 'like', $params['city'] . '%')
                ->where('province_id', $provinceData->id)
                ->first();
            if (empty($city)) {
                return response()->json([
                    'code' => 1000,
                    'message' => '市级数据有误'
                ]);
            }
            DB::beginTransaction();
            $model = new Warranty();
            $model->first_name = $params['first_name'];
            $model->extension = $params['region'] ?? '中国大陆';
            $model->email_address = $params['email'];
            $model->phone_number = $params['phone_number'];
            $model->address = $params['address'];
            $model->license_plate = $params['license_plate'];
            $model->vin_number = $params['vin_number'];
            $model->installer_name = $params['installer_name'];
            $model->installation_date = $params['installation_date'];
            $model->installation_price = $params['installation_price'];
            $model->province_id = $city->province_id;
            $model->city = $city->id;
            $model->region_id = 1;
            $model->warranty_id = makeWarrantyId($model->installation_date);
            $model->dealer_name = $dealer->abbr;
            $model->user_id = $dealer->id;
            $model->distributor_id = $distributor->id;
            $model->distributor_name = $distributor->abbr;
            $year = $params['year'];
            $make_name = $params['make_name'];
            $model_name = $params['model_name'];
            $make_id = getMakeId($make_name, $year);
            if (empty($make_id)) {
                $makeModel = new MakeMaster();
                $makeModel->year_id = $year;
                $makeModel->english_value = $make_name;
                $makeModel->traditional_chiness_value = $make_name;
                $makeModel->simplified_chiness_value = $make_name;
                $makeModel->save();
                $make_id = $makeModel->id;
                makeLangFiles();
            }
            $model_id = getModelId($model_name, $make_id);
            if (empty($model_id)) {
                $modelModel = new ModelMaster();
                $modelModel->make_id = $make_id;
                $modelModel->english_value = $model_name;
                $modelModel->traditional_chiness_value = $model_name;
                $modelModel->simplified_chiness_value = $model_name;
                $modelModel->save();
                $model_id = $modelModel->id;
                makeLangFiles();
            }
            $model->year_id = $year;
            $model->make_id = $make_id;
            $model->model_id = $model_id;
            $model->approved = 3;
            $model->save();

            foreach ($params['converages'] as $cover) {
                if (empty($cover['film_type_name']) || empty($cover['part']) || empty($cover['roll_number']) || empty($cover['length']) || empty($cover['precut_or_manual']) || !in_array($cover['precut_or_manual'], [1, 2])) {
                    DB::rollback();
                    return response()->json([
                        'code' => 2,
                        'msg' => '安装位置数据不完整！'
                    ]);
                }
                if (!is_numeric($cover['length']) || $cover['length'] <= 0) {
                    DB::rollback();
                    return response()->json([
                        'code' => 2,
                        'msg' => '安装位置数据异常！'
                    ]);
                }
                $filmType = DB::table('film_type_master')->where('simplified_chiness_value', $cover['film_type_name'])->first();
                if (empty($filmType)) {
                    DB::rollback();
                    return response()->json([
                        'code' => 3,
                        'msg' => '膜' . $cover['film_type_name'] . '不存在！'
                    ]);
                }
                $part = DB::table('part_master')->where('simplified_chiness_value', $cover['part'])->first();
                if (empty($part)) {
                    DB::rollback();
                    return response()->json([
                        'code' => 3,
                        'msg' => '部位' . $cover['part'] . '不存在！'
                    ]);
                }
                $converage['warranty_id'] = $model->id;
                $converage['part_id'] = $part->id;
                $converage['roll_number'] = $cover['roll_number'];
                $converage['length'] = $cover['length'];
                $converage['width'] = $cover['width'];
                $converage['film_type_id'] = $filmType->id;
                $converage['precut_or_manual'] = $cover['precut_or_manual'];
                $converage['start_time'] = "";
                $converage['end_time'] = "";
                if (!empty($filmType->warranty_days)) {
                    $starTime = $model->installation_date ? strtotime($model->installation_date) : time();
                    $endTime = strtotime("+$filmType->warranty_days days", $starTime);
                    $converage['start_time'] = $starTime;
                    $converage['end_time'] = $endTime;
                }
                $converage['created_at'] = gDate();
                $converage['updated_at'] = gDate();
                DB::table('warranty_to_vehicle_coverage')->insert($converage);
            }
            $images = explode(',', $params['images']);
            foreach ($images as $k => $v) {
                $fileName = Str::random(32) . '.jpg';
                $imageUrl = (new UploadService())->uploadAliOss(file_get_contents($v), $fileName);
                if (empty($imageUrl['oss-request-url'])) {
                    return response()->json([
                        'code'  => 1000,
                        'msg'   => '上传图片异常！'
                    ]);
                }
                $url = str_replace('https://xpel-dengwho.oss-cn-shanghai.aliyuncs.com', 'https://image-xpel.dengwho.com', $imageUrl['oss-request-url']);
                $item = [];
                $item['warranty_id'] = $model->id;
                $item['created_at'] = gDate();
                $item['updated_at'] = gDate();
                $item['image_src'] = $url;
                $item['part_id'] = $k + 1;
                DB::table('warranty_image')->insert($item);
            }
            DB::commit();
        } catch (\Exception $exception) {
            Log::error($exception->getMessage());
            DB::rollback(); //数据库回滚
            return response()->json([
                'code'  => 1000,
                'msg'   => '服务器错误,稍后重试！'
            ]);
        }

        return response()->json([
            'code'  => 0,
            'msg'   => 'success',
            'warranty_id'   => $model->warranty_id
        ]);
    }

    public function rollRestlen(Request $request)
    {
        $this->checkRequestData($request);
        $content = $request->input('content');
        $content = json_decode($content, true);
        if (empty($content['shop_code']) || empty($content['roll_number'])) {
            return response()->json([
                'code'  => 1000,
                'message'   => '缺少数据'
            ]);
        }
        $shopCode = $content['shop_code'];
        $rollNumber = $content['roll_number'];
        $dealer = Admin::withTrashed()->where('unique_id', $shopCode)->first();
        if (empty($dealer->id) || empty($dealer->abbr)) {
            return response()->json([
                'code' => 1,
                'msg' => '装贴门店为空或不存在！',
            ]);
        }
        $model = DB::table('roll_master')
            ->select('roll_master.id', 'roll_master.roll_number', 'roll_restlen.restlen', 'film_type_master.simplified_chiness_value as film_type_name')
            ->leftJoin('roll_restlen', 'roll_master.roll_number',   'roll_restlen.roll_number')
            ->leftJoin('film_type_master', 'film_type_master.id', 'roll_master.film_type_id')
            ->where('roll_master.roll_number', $rollNumber);
        $data = $model->where('roll_restlen.restlen', '>', 0)
            ->where('roll_restlen.user_id', $dealer->id)
            ->get();
        Log::info($data);
        return response()->json([
            'code' => 0,
            'data' => $data
        ]);
    }

    //T9电研社官网接口
    public function getProviderListT9(Request $request)
    {
        try {
            $this->checkRequestData($request);
        } catch (\Exception $exception) {
            return response()->json([
                'code'  => $exception->getCode() ?: 10000,
                'msg'   => $exception->getMessage() ?: '系统异常'
            ]);
        }
        $content = $request->input('content');
        $content = json_decode($content, true);
        if (empty($content['page'])) {
            return response()->json([
                'code'  => 10000,
                'msg'   => '缺少分页数据'
            ]);
        }
        $page = $content['page'];
        $pageSize = $content['pageSize'] ?? 20;

        $model = DB::table('users')
            ->leftJoin('store_info', 'users.id', 'store_info.user_id')
            ->leftJoin('dealer', 'users.id', 'dealer.user_id')
            ->leftJoin('cities', 'cities.id', 'users.city')
            ->leftJoin('province_master', 'province_master.id', 'users.province_id');

        $total = $model
            ->select(
                'users.id',
                'users.company_name',
                'users.abbr',
                'users.address',
                'users.email_address',
                'users.phone_number',
                'users.zsdj',
                'cities.simplified_chiness_value as city_name',
                'users.mdtype',
                'province_master.simplified_chiness_value as province_name',
                'users.user_type',
                'dealer.store_pictures',
                'store_info.video_url',
                'store_info.detail',
                'users.unique_id as store_code',
                'store_info.open_time',
                'store_info.close_time',
                'store_info.start_date',
                'store_info.end_date',
                'store_info.picture_url',
                'dealer.cert_person as persons',
                'store_info.qrcode_url',
                'store_info.front_show',
                'store_info.is_advanced',
                'users.status',
                'store_info.honor',
                'users.check_status',
                'users.category_code',
                'users.category_name'
            )
            ->whereNull('users.deleted_at')
            ->where('status', 1)
            ->where('users.user_type', 3)
            ->where('mdtype', '=', 8)
            ->count();
        $firstData = $model
            ->select(
                'users.id',
                'users.company_name',
                'users.abbr',
                'users.address',
                'users.email_address',
                'users.phone_number',
                'users.zsdj',
                'cities.simplified_chiness_value as city_name',
                'users.mdtype',
                'province_master.simplified_chiness_value as province_name',
                'users.user_type',
                'dealer.store_pictures',
                'store_info.video_url',
                'store_info.detail',
                'users.unique_id as store_code',
                'store_info.open_time',
                'store_info.close_time',
                'store_info.start_date',
                'store_info.end_date',
                'store_info.picture_url',
                'dealer.cert_person as persons',
                'store_info.qrcode_url',
                'store_info.front_show',
                'store_info.is_advanced',
                'users.status',
                'store_info.honor',
                'users.check_status',
                'users.category_code',
                'users.category_name'
            )
            ->whereNull('users.deleted_at')
            ->where('status', 1)
            ->where('mdtype', '=', 8)
            ->orderByRaw(' CONVERT(abbr USING gbk)')
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->get();
        $count = 0;
        // $result = [];
        if (!empty($firstData) && !$firstData->isEmpty()) {
            $result = [];
            $dealerIdArr = [];
            foreach ($firstData as $item) {
                if ($item->is_advanced == 1) {
                    $dealerIdArr[] = $item->id;
                    $result[] = $item;
                }
            }

            $dealerId = $firstData->pluck('id')->toArray();

            $sql = 'SELECT SUM(xpel_warranty_roll_detail_stat.score) as total_score, dealer_id FROM xpel_warranty_roll_detail_stat WHERE dealer_id IN (' . implode(',', $dealerId) . ')';
            $sql .= ' AND product_type_id=1 AND create_date>="' . date("Y-m", strtotime('-1 month')) . '" AND create_date<"' . date("Y-m") . '" AND dealer_id!=dist_id';
            $sql .= ' GROUP BY dealer_id ORDER BY total_score DESC';
            $warrantyResult = DB::select($sql);
            if (!empty($warrantyResult)) {
                foreach ($warrantyResult as $item) {
                    if (in_array($item->dealer_id, $dealerIdArr)) {
                        continue;
                    }
                    $dealerIdArr[] = $item->dealer_id;
                    foreach ($firstData as $value) {
                        if ($value->id === $item->dealer_id) {
                            $result[] = $value;
                            break;
                        }
                    }
                }
            }

            // foreach ($firstData as $item) {
            //     if (!in_array($item->id, $dealerIdArr)) {
            //         $result[] = $item;
            //     }
            // }

            $count = count($result);
        }

        if ($count < $pageSize) {
            if ($count > 0) {
                $start = 0;
            } else {
                $start = ($page - 1) * $pageSize - $total;
            }
            $twoModel = DB::table('users')
                ->leftJoin('store_info', 'users.id', 'store_info.user_id')
                ->leftJoin('dealer', 'users.id', 'dealer.user_id')
                ->leftJoin('cities', 'cities.id', 'users.city')
                ->leftJoin('province_master', 'province_master.id', 'users.province_id');
            $twoData = $twoModel
                ->select(
                    'users.id',
                    'users.company_name',
                    'users.abbr',
                    'users.address',
                    'users.email_address',
                    'users.phone_number',
                    'users.zsdj',
                    'cities.simplified_chiness_value as city_name',
                    'users.mdtype',
                    'province_master.simplified_chiness_value as province_name',
                    'users.user_type',
                    'dealer.store_pictures',
                    'store_info.video_url',
                    'store_info.detail',
                    'users.unique_id as store_code',
                    'store_info.open_time',
                    'store_info.close_time',
                    'store_info.start_date',
                    'store_info.end_date',
                    'store_info.picture_url',
                    'dealer.cert_person as persons',
                    'store_info.qrcode_url',
                    'store_info.front_show',
                    'store_info.is_advanced',
                    'users.status',
                    'store_info.honor',
                    'users.check_status'
                )
                ->whereNull('users.deleted_at')
                ->where('status', 1)
                ->where('users.user_type', 3)
                ->where('mdtype', "=", 8)
                ->offset($start)
                ->limit($pageSize)
                ->orderByRaw(' CONVERT(abbr USING gbk)')
                ->get();
            if (!empty($twoData) && $twoData->isNotEmpty()) {
                $dealerIdArr = [];
                foreach ($twoData as $item) {
                    if ($item->is_advanced == 1) {
                        $dealerIdArr[] = $item->id;
                        $result[] = $item;
                    }
                }

                $dealerId = $twoData->pluck('id')->toArray();
                $sql = 'SELECT SUM(xpel_warranty_roll_detail_stat.score) as total_score, dealer_id FROM xpel_warranty_roll_detail_stat WHERE dealer_id IN (' . implode(',', $dealerId) . ')';
                $sql .= ' AND product_type_id=1 AND create_date>="' . date("Y-m", strtotime('-1 month')) . '" AND create_date<"' . date("Y-m") . '" AND dealer_id!=dist_id';
                $sql .= ' GROUP BY dealer_id ORDER BY total_score DESC';
                $warrantyTwoResult = DB::select($sql);
                if (!empty($warrantyTwoResult)) {
                    foreach ($warrantyTwoResult as $item) {
                        if (in_array($item->dealer_id, $dealerIdArr)) {
                            continue;
                        }
                        $dealerIdArr[] = $item->dealer_id;
                        foreach ($twoData as $value) {
                            if ($value->id === $item->dealer_id) {
                                $result[] = $value;
                                break;
                            }
                        }
                    }
                }
                foreach ($twoData as $item) {
                    if (!in_array($item->id, $dealerIdArr)) {
                        $result[] = $item;
                    }
                }
            }
        }

        $response = [];
        foreach ($result as $item) {
            unset($item->total_score);
            $item->status = $item->status == 1 && $item->check_status == 1 ? 1 : 0;
            $item->qrcode_url = $item->qrcode_url ? env('APP_URL') . $item->qrcode_url : '';
            if (!empty($item->store_pictures)) {
                $pictures = explode(',', $item->store_pictures);
                $item->picture_url = [];
                foreach ($pictures as $picture) {
                    $item->picture_url[] = env('APP_URL') . $picture;
                }
            } else {
                $item->picture_url = '';
            }

            $item->mdtype = 'T9电研社';
            if ($item->user_type === 2) {
                $item->store_code = '';
            }
            if (!empty($item->persons)) {
                $persons = json_decode($item->persons, true);
                if (!empty($persons)) {
                    $item->persons = $persons;
                }
            }

            $response[] = $item;
        }

        return response()->json([
            'code'  => 0,
            'data'  => $response
        ]);
    }
}
